import { FileUtil, HvigorNode, HvigorTask } from "@ohos/hvigor";
import { OhosHapContext, OhosPluginId, Target } from "@ohos/hvigor-ohos-plugin";
import FileUtils from "../utils/FileUtils";
import ObjectUtils from "../utils/ObjectUtils";
import GeneratorStore from "./GeneratorStore";

export function CopyRouterMapTask(
  target: Target,
  node: HvigorNode
): HvigorTask {
  const targetName = target.getTargetName();
  return {
    name: `${targetName}@CopyRouterMapTask`,
    run: () => {
      doActionTask(target, node);
    },
    dependencies: [`${target.getTargetName()}@ProcessRouterMap`],
    postDependencies: [`${target.getTargetName()}@ProcessResource`],
  };
}

function doActionTask(target: Target, node: HvigorNode) {
  const hapContext = node.getContext(
    OhosPluginId.OHOS_HAP_PLUGIN
  ) as OhosHapContext;

  const moduleOpt = hapContext.getModuleJsonOpt();
  ObjectUtils.ensureNestedObject(moduleOpt, ["module", "routerMap"]);
  const routerMapFileName = moduleOpt.module.routerMap.replace("$profile:", "");

  const outputRouterMapPath = `${node
    .getNodeDir()
    .getPath()}/build/${target.getTargetName()}/intermediates/router_map/${target.getTargetName()}/${routerMapFileName}.json`;

  const routerContentJsonStr =
    FileUtil.readFileSync(outputRouterMapPath).toString();
  const routerContent = JSON.parse(routerContentJsonStr);
  routerContent.routerMap?.forEach((item) => {
    item.customData.__nlRootModuleName__ =
      hapContext.getModuleJsonOpt().module.name;
  });

  const copyToRawFilePath = `${node
    .getNodeDir()
    .getPath()}/src/main/resources/rawfile/nl_router_map.json`;
  FileUtils.ensureFileSync(copyToRawFilePath);

  FileUtils.writeFileSync(copyToRawFilePath, JSON.stringify(routerContent));
  
  GeneratorStore.pushFilePath(copyToRawFilePath);
}
